//index.js
//获取应用实例
const app = getApp()
var util = require('../../utils/util.js');
Page({
  data: {
    shoplist: [],
    page: 1,
    pagesize:15,
    hasMore: true,
  },
  //事件处理函数
  bindViewTap: function(e) {
    var that = this  
    wx.navigateTo({
      url: 'details?id=' + e.currentTarget.id
    })
  },
  onLoad: function () {
    wx.setNavigationBarTitle({
      title: '首页'
    })
    
    var that = this;
    that.getGoodsList();
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      // wx.getUserInfo({
      //   success: res => {
      //     app.globalData.userInfo = res.userInfo
      //     this.setData({
      //       userInfo: res.userInfo,
      //       hasUserInfo: true
      //     })
      //   }
      // })
    }
  },

  onShow: function (){
    var that = this;
    
  },

  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  //商品列表 （用户端 首页）
  getGoodsList: function () {
    var that = this;
    wx.showLoading({ title: '加载中' });
    var url = util.URL.goods_list + '?p=' + that.data.page + '&pagesize=' + that.data.pagesize;
    util.GET(url, function (sData) {
      wx.hideLoading();
      var more = true;
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
      that.setData({  
        shoplist: sData.info,
        page: 2,
        hasMore: more 
      })
      wx.stopPullDownRefresh();
    }, function (eData) {
      wx.hideLoading();
    });
  },
  
  /**
  * 页面上拉触底事件的处理函数
  */
  onReachBottom: function () {
    //加载更多
    var that = this;
    var more=that.data.hasMore;
    if(more){
      this.getMoreGoodsList();
    }else{
      wx.showToast({
        title: '已加载全部数据',
        icon: 'none'
      })
    }
  },
  //加载更多商品
  getMoreGoodsList: function () {
    var that = this;
    wx.showLoading({ title: '加载中' });
    var paras = { p: that.data.page, pagesize: that.data.pagesize };
    var url = util.URL.goods_list + '?p=' + that.data.page + '&pagesize=' + that.data.pagesize;

    util.GET(url, function (sData) {
      wx.hideLoading();
      var more = true;
      var newLists = that.data.shoplist.concat(sData.info);
      if (sData.info.length <= 0) {
        more = false;
        wx.showToast({
          title: '已加载全部数据',
          icon: 'none',
          duration: 500
        })
      }
      that.setData({
        shoplist: newLists,
        page: that.data.page + 1,
        hasMore: more
      })
    }, function (eData) {
      wx.hideLoading();
    });
  }
})
